const Koa = require('koa')
const { resolve } = require('path')
const bodyParser = require('koa-bodyparser')
const koaStatic = require('koa-static')
// const koaCompress = require('koa-compress')

const auth = require('./middleware/auth')
const { httpLog, ctxLog, logger } = require('./middleware/logger')

const router = require('./routes')
const getAvailablePort = require('./utils/port')

require('./utils/window')

const server = new Koa()

// 日志记录
server.use(httpLog())
server.use(ctxLog())

// 压缩响应
// server.use(koaCompress())

// 解析请求参数
server.use(bodyParser())

// 设置打包后文件夹为静态文件夹
server.use(koaStatic(resolve(process.cwd(), './dist')))

// 获取验证ID
server.use(auth())

// 配置路由
server.use(router.routes())
server.use(router.allowedMethods())

// 错误处理
server.on('error', (err) => {
  logger.error(err.stack || '')
})

/**
 * 启动服务
 */
async function startServer () {
	const port = await getAvailablePort(3000)
	server.listen(port, () => {
		console.log(`form-render server is running on ${port}`)
	})
}

startServer()
